/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package servlets;

import astralmlprocessor.AstralMLCreator;
import astralmlprocessor.PuntoAstro;
import com.oreilly.servlet.MultipartRequest;
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 *
 * @author age
 */
public class CargarSerie extends HttpServlet {

    private static String filePath;

    @Override
    public void init(ServletConfig config) throws ServletException {
        // Obtener un contexto para ubicar los archivos 
        // en la ruta del servidor especificada (FormulaGraph/build/web/upload-files)
        filePath = config.getServletContext().getRealPath("/") + "upload-files";
    }

    /** 
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");

        // Limite de tamaño de fichero 5 MB
        MultipartRequest mpr = new MultipartRequest(request, filePath, 5 * 1024 * 1024);
        
        String filtro = (String)mpr.getParameter("filtro");
        String datejd = (String)mpr.getParameter("datejd");
        String observador = (String)mpr.getParameter("observador");
        String texp = (String)mpr.getParameter("texp");
        String notseries = (String)mpr.getParameter("notseries");
        String notobserver = (String)mpr.getParameter("notobserver");
        
        /*
        // Desglose de nombre de fichero
        String [] nameParts = mpr.getFile("file1").getName().split("_");
        for (int i=0; i<nameParts.length; i++) {
            if (i == 0) { // Filtro
                out.println("x"+": "+nameParts[i]);
            } else if (i == 1) { // Observador
                out.println("x"+": "+nameParts[i]);
            }
        }
        */
                
        // Obtener puntos del fichero
        ArrayList<PuntoAstro> puntos = new ArrayList<PuntoAstro>();
        FileInputStream fstream = new FileInputStream(mpr.getFile("file1"));
        DataInputStream in = new DataInputStream(fstream);
        BufferedReader br = new BufferedReader(new InputStreamReader(in));
        String strLine;
        while ((strLine = br.readLine()) != null)   {
            String [] point = strLine.split("\\p{Space}+");
            PuntoAstro punto = new PuntoAstro();
            String comment = "";
            for (int i=0; i<point.length; i++) {
                if (i == 0) {
                    punto.setJd(Double.parseDouble(point[i]));
                } else if (i == 1) {
                    punto.setMg(Double.parseDouble(point[i]));
                } else if (i == 2) {
                    punto.setEr(Double.parseDouble(point[i]));
                } else if (i >= 3) {
                    if (!comment.isEmpty()) comment += " ";
                    comment += point[i];
                }
            }
            punto.setComment(comment);
            puntos.add(punto);
        }
        in.close(); 
        
        AstralMLCreator.getInstance().addSesion(filtro, observador, datejd, texp, notseries, notobserver, puntos);

        request.setAttribute("estado", "bdcreada");
        
        RequestDispatcher rd = request.getRequestDispatcher("/astronomy.jsp");
        rd.forward(request, response);
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /** 
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}
